package com.laiketui.core.config;

import com.laiketui.core.domain.Result;
import com.laiketui.core.exception.LaiKeAPIException;
import org.apache.ibatis.binding.BindingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获处理类
 */
@ControllerAdvice
public class GlobalLaiKeAPIExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Result> handleException(HttpServletRequest request, Exception e) {
        // 检查请求属性中的异常
        Object filterException = request.getAttribute("filterException");
        if (filterException instanceof LaiKeAPIException) {
            LaiKeAPIException laiKeAPIException = (LaiKeAPIException) filterException;
            logger.error("异常编码：{},内容：{}", laiKeAPIException.getCode(), laiKeAPIException.getMessage());
            return new ResponseEntity<>(Result.error(laiKeAPIException.getCode(), laiKeAPIException.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        } else if (e instanceof LaiKeAPIException) {
            LaiKeAPIException laiKeAPIException = (LaiKeAPIException) e;
            logger.error("异常编码：{},内容：{}", laiKeAPIException.getCode(), laiKeAPIException.getMessage());
            return new ResponseEntity<>(Result.error(laiKeAPIException.getCode(), laiKeAPIException.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }else  if (e instanceof BindException){
            BindingResult bindingResult = ((BindException) e).getBindingResult();
            StringBuilder sb = new StringBuilder("校验失败:");
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
            }
            String msg = sb.toString();
            logger.error(msg);
           return  new ResponseEntity<>(Result.error("20019",msg), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        logger.error("其他异常：{},内容：{}", "20019", e.getMessage());
        return new ResponseEntity<>(Result.error("20019", e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}